<?php
// +----------------------------------------------------------------------
// | Description: 1
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
// | Date: 2018-01-25 09:50:58
// +----------------------------------------------------------------------

namespace app\client\model;

use app\client\model\OrdersItem;
use app\client\model\Sku;
use app\common\model\CommonClient;
use think\Db;

class Order extends CommonClient
{
    protected $fuzzyConditions = ['UserName', 'RealName', 'CellPhone', 'ReceiverPhone', 'ReceiverName', 'AddrDetail', 'AddrProvince', 'AddrCity', 'AddrArea'];
    protected $clearConditions = ['Id', 'IsDelete', 'UserName', 'UserId', 'Weight', 'OrderTotal', 'GoodsTotal', 'DiscountAmount', 'RealPay', 'OrderStatus'];
    protected $returnFields = '
        shop_orders.*,
        shop_orders_items.IsRated,
        shop_orders_items.ProductName,
        shop_orders_items.ProductId,
        shop_orders_items.SkuId,
        shop_orders_items.ImgPath,
        shop_orders_items.SKUContent,
        shop_orders_items.SalePrice
    ';

    protected $rangeConditions = ['CreateDate', 'UpdateDate'];
    protected $union_fuzzyConditions = null;
    protected $foreignConditions = [
        'shop_orders_items' => ['OrderId', 'Id'],
    ];
    protected $name = 'shop_orders';

    /**
     * 解析搜索条件
     */
    public function getDataList()
    {
        $this->page = $this->param['page'] or 1;
        $this->limit = $this->param['limit'] or $this->limit;
        $this->orderByString = $this->param['orderByString'];
        // $this->param['IsDelete'] = 0;   // 开启软删除 

        $this->specialCondition();
        $this->M_fuzzy();
        $this->M_clear();
        $this->M_range();
        $this->M_union_field();
        $this->M_UnionSelect();
        $this->M_order();
        // $this->where($this -> name.'.IsDelete', 0);

        if ($this->limit == -1) {
            $resData = $this->field($this->returnFields)->select();
        } else {
            $resData = $this->field($this->returnFields)->page($this->page, $this->limit)->select();
        }
        // p($this -> getlastsql());

        // 分页特殊处理
        $this -> foreignConditions = null;

        $this->specialCondition();
        $this->M_fuzzy();
        $this->M_clear();
        $this->M_range();
        $this->M_union_field();
        $this->M_UnionSelect();
        $this->M_order();
        // $this->where('IsDelete', 0);

        $dataCount = $this->count();
        $data['list'] = $resData;
        $data['dataCount'] = $dataCount;
        return $this->filter($data);
    }

    /**
     * 数据处理 形成想要的数据结构
     *
     * @return void
     */
    public function filter($data)
    {
        // p($data);
        // return $data;
        $list = $data['list'];
        // $list = ;
        // p($list);
        foreach ($list as $k => $v) {
            $list[$k]['ProductsList'] = [];
        }
        $temp = [];
        // $ProductsListTemp = [];
        foreach ($list as $k => $v) {
            $ProductsListTemp = 'v'.$v['Id'];
            if (count($temp) == 0) {
                $v['Id'] = (string) $v['Id'];
                $temp[] = $v;
                $$ProductsListTemp[] = [
                    'IsRated'   => $v['IsRated'],
                    'ProductId' => $v['ProductId'],
                    'SkuId' => $v['SkuId'],
                    'ProductName' => $v['ProductName'],
                    'ImgPath' => $v['ImgPath'],
                    'SalePrice' => $v['SalePrice'],
                    'SKUContent' => json_decode($v['SKUContent']),
                ];
                $temp[0]['ProductsList'] = $$ProductsListTemp;
                unset($temp[0]['IsRated']);
                unset($temp[0]['ProductId']);
                unset($temp[0]['SkuId']);
                unset($temp[0]['ProductName']);
                unset($temp[0]['ImgPath']);
                unset($temp[0]['SalePrice']);
                unset($temp[0]['SKUContent']);
            } else {

                foreach ($temp as $kk => $vv) {
                    if ($vv['Id'] == $v['Id']) {
                        // p($v['ProductName']);
                        // p($temp[$kk]);
                        
                        $$ProductsListTemp[] = [
                            'IsRated'   => $v['IsRated'],
                            'ProductId' => $v['ProductId'],
                            'SkuId' => $v['SkuId'],
                            'ProductName' => $v['ProductName'],
                            'ImgPath' => $v['ImgPath'],
                            'SalePrice' => $v['SalePrice'],
                            'SKUContent' => json_decode($v['SKUContent']),
                        ];
                        $temp[$kk]['ProductsList'] = $$ProductsListTemp;
                        // p($temp[$kk] -> ProductsList);
                        unset($temp[$kk]['IsRated']);
                        unset($temp[$kk]['ProductId']);
                        unset($temp[$kk]['SkuId']);
                        unset($temp[$kk]['ProductName']);
                        unset($temp[$kk]['ImgPath']);
                        unset($temp[$kk]['SalePrice']);
                        unset($temp[$kk]['SKUContent']);
                        // p(11);
                        continue 2;
                    }
                }
                $v['Id'] = (string) $v['Id'];
                $temp[] = $v;
                $$ProductsListTemp[] = [
                    'IsRated'   => $v['IsRated'],
                    'ProductId' => $v['ProductId'],
                    'SkuId' => $v['SkuId'],
                    'ProductName' => $v['ProductName'],
                    'ImgPath' => $v['ImgPath'],
                    'SKUContent' => json_decode($v['SKUContent']),
                ];
                $temp[count($temp) - 1]['ProductsList'] = $$ProductsListTemp;
                unset($temp[count($temp) - 1]['IsRated']);
                unset($temp[count($temp) - 1]['SkuId']);
                unset($temp[count($temp) - 1]['ProductId']);
                unset($temp[count($temp) - 1]['ProductName']);
                unset($temp[count($temp) - 1]['ImgPath']);
                unset($temp[count($temp) - 1]['SalePrice']);
                unset($temp[count($temp) - 1]['SKUContent']);
            }
        }
        $data['list'] = $temp;
        // p($temp);
        return $data;
    }

    /**
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    public function object_to_array($obj)
    {
        $obj = (array) $obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array) $this->object_to_array($v);
            }
        }

        return $obj;
    }

    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array                    $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param)
    {
        // p($param);
        // 通过该订单包含的所有商品进行计算得出
        // $param['SkuAndNum'] = [
        //     [1, 10],
        //     [2, 5],
        //     [3, 29],
        // ];
        $SkuAndNum = $param['SkuAndNum'];
        $param['PaymentTypeId'] = 1;

        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }

        // $data['Id'] = $this->getUniqueOrderId(); //  唯一订单编号
        // $OrderId = $data['Id'];
        $data['PaymentTypeId'] = $param['PaymentTypeId']; // 余额支付

        foreach ($SkuAndNum as $k => $v) {
            $skuids[] = $v[0];
        }
        $GoodsTotal = 0;
        $weight = 0;
        $skuInfo = Db::table('shop_goods_sku')->where('Id', 'in', $skuids)->select();
        foreach ($skuInfo as $k => $v) {
            foreach ($SkuAndNum as $kk => $vv) {
                if ($v['Id'] == $vv[0]) {
                    $GoodsTotal += $v['SalePrice'] * $vv[1]; // 商品总金额
                    $weight += $v['Weight'] * $vv[1]; // 商品总重量
                }
            }
        }
        $data['Weight'] = $weight;
        $Freight = $this->getFreight(); // 通过物流规格 + 收货地址 + 商品重量 + 商品总价 等等信息计算出 运费
        $DiscountAmount = $this->getDiscountAmount(); // 查询相关活动 计算出总折扣金额
        $data['Freight'] = $Freight;
        $data['GoodsTotal'] = $GoodsTotal;
        $data['OrderTotal'] = $GoodsTotal + $Freight;
        $data['RealPay'] = $GoodsTotal + $Freight - $DiscountAmount;
        $data['DiscountAmount'] = $DiscountAmount;
        $data['RefundAmount'] = $data['RealPay']; // 退款金额等于付款金额

        // 获得收货人信息
        $addrInfo = Db::table('shop_members_address')->where(['UserId' => $param['UserId']])->find($param['AddressId']);
        if (!$addrInfo) {
            $this->error = '收货地址不能为空';
            return false;
        }

        $data['ReceiverPhone'] = $addrInfo['ReceiverPhone'];
        $data['ReceiverName'] = $addrInfo['ReceiverName'];
        $data['AddrProvince'] = $addrInfo['AddrProvince'];
        $data['AddrCity'] = $addrInfo['AddrCity'];
        $data['AddrArea'] = $addrInfo['AddrArea'];
        $data['AddrDetail'] = $addrInfo['AddrDetail'];

        // 获得收货人账户信息
        // $userInfo = session('MemberInfo');
        $userInfo = [
            'UserName' => "orchief",
            'RealName' => 'orchief',
            'CellPhone' => '186464634',
        ];
        $data['UserName'] = $userInfo['UserName'];
        $data['RealName'] = $userInfo['RealName'];
        $data['CellPhone'] = $userInfo['CellPhone'];
        $data['UserId'] = $param['UserId'];

        $this->startTrans();
        try {
            $this->data($data)->allowField(true)->save(); // 订单
            $OrderId = $this->getlastInsID();

            // 订单商品表数据
            foreach ($SkuAndNum as $k => $v) {

                foreach ($skuInfo as $kk => $vv) {
                    if ($vv['Id'] == $v[0]) {
                        $skuItem = $vv;
                    }
                }

                $ProductInfo = Db::table('shop_goods_products')->field('')->find($skuItem['ProductId']);
                $ProductName = $ProductInfo['ProductName'];
                $ProductCode = $ProductInfo['ProductCode'];
                $ImgPath = $ProductInfo['ImgPath'];

                $SKUContentArr = [];
                // 查询出该商品 非基本规格信息
                $items = Db::table('shop_goods_sku_items')
                    ->join('shop_goods_attribute_values', 'shop_goods_sku_items.ValueId = shop_goods_attribute_values.Id')
                    ->join('shop_goods_attributes', 'shop_goods_sku_items.AttributeId = shop_goods_attributes.Id')
                    ->where(['SkuId' => $skuItem['Id']])->select();

                foreach ($items as $kk => $vv) {
                    $SKUContentArr[] = [
                        'AttributeName' => $vv['AttributeName'],
                        'ValueStr' => $vv['ValueStr'],
                    ];
                }

                // 基本规格信息
                $baseitems = Db::table('shop_goods_product_attributes')
                    ->join('shop_goods_attribute_values', 'shop_goods_product_attributes.ValueId = shop_goods_attribute_values.Id')
                    ->join('shop_goods_attributes', 'shop_goods_product_attributes.AttributeId = shop_goods_attributes.Id')
                    -> where(['IsSku' => 0])
                    ->where(['ProductId' => $skuItem['ProductId']])->select();

                foreach ($baseitems as $kk => $vv) {
                    $SKUContentArr[] = [
                        'AttributeName' => $vv['AttributeName'],
                        'ValueStr' => $vv['ValueStr'],
                    ];
                }

                $SKUContent = json_encode($SKUContentArr, JSON_UNESCAPED_UNICODE);

                $dataSkus[] = [
                    'OrderId' => $OrderId,
                    'SkuId' => $v[0],
                    'ProductId' => $skuItem['ProductId'],
                    'Quantity' => $v[1],
                    'CostPrice' => $skuItem['CostPrice'],
                    'SalePrice' => $skuItem['SalePrice'],
                    'Weight' => $skuItem['Weight'],
                    'SKUContent' => $SKUContent,
                    'ProductName' => $ProductName,
                    'ProductCode' => $ProductCode,
                    'ImgPath' => $ImgPath,
                ];
            }

            $OrdersItem = new OrdersItem();
            $Sku = new Sku();
            foreach ($SkuAndNum as $k => $v) {
                $Sku->where(['Id' => $v[0]])->setDec('Stock', $v[1]);
                $Sku->where(['Id' => $v[0]])->setInc('SalesVolume', $v[1]);
            }
            // $res = $Sku -> query("UPDATE shop_goods_sku SET ");
            // p($res);
            $OrdersItem->allowField(true)->saveAll($dataSkus); // 订单商品表
            // p($data);

            $this->commit();
            return ['OrderId' => $OrderId];
        } catch (\Exception $e) {
            $this->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function getUniqueOrderId()
    {
        return (int) date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 6, 13), 1))), 0, 8);
    }

    public function getFreight()
    {
        return 0;
    }

    public function getDiscountAmount()
    {
        return 0;
    }

    public function OrderCount($param)
    {
        // 不同种类订单的统计
        $status0 = $this->where(['OrderStatus' => 0, 'UserId' => $param['UserId']])->count();
        $status1 = $this->where(['OrderStatus' => 1, 'UserId' => $param['UserId']])->count();
        $status2 = $this->where(['OrderStatus' => 2, 'UserId' => $param['UserId']])->count();
        $status3 = $this->where(['OrderStatus' => 3, 'UserId' => $param['UserId']])->count();
        $status4 = $this->where(['OrderStatus' => 4, 'UserId' => $param['UserId']])->count();
        $status5 = $this->where(['OrderStatus' => 5, 'UserId' => $param['UserId']])->count();
        $data = [
            $status0,
            $status1,
            $status2,
            $status3,
            $status4,
            $status5,
        ];
        return $data;
    }
}
